package com.chushouya.product.service.api.impl;

import com.chushouya.product.dao.entity.*;
import com.chushouya.product.dao.repository.*;
import com.general.framework.core.exception.Ex;
import com.general.framework.core.lang.Jsons;
import com.chushouya.product.constants.EvaluateTypeEnum;
//=====product.dao.entity.*;
//=====product.dao.repository.*;
import com.chushouya.product.dao.entity.*;
import com.chushouya.product.dao.repository.*;
import com.chushouya.product.dto.admin.attribute.AttributeItemQuery;
import com.chushouya.product.dto.admin.attribute.AttributeItemValueQuery;
import com.chushouya.product.dto.admin.evaluateitem.EvaluateItemQuery;
import com.chushouya.product.dto.admin.evaluateitem.EvaluateItemValueQuery;
import com.chushouya.product.dto.admin.productsku.SkuGenerateDTO;
import com.chushouya.product.dto.api.evaluate.EvaluateListApiDTO;
import com.chushouya.product.dto.api.evaluate.EvaluateValueApiDTO;
import com.chushouya.product.service.admin.ProductSkuService;
import com.chushouya.product.service.api.EvaluateApiService;
import com.chushouya.product.service.api.ResolveEvaluateApiService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ResolveEvaluateApiServiceImpl implements ResolveEvaluateApiService {

    @Resource
    private EvaluateApiService evaluateApiService;

    @Resource
    private ProductRepository productRepository;

    @Resource
    private AttributeItemRepository attributeItemRepository;

    @Resource
    private AttributeItemValueRepository attributeItemValueRepository;

    @Resource
    private EvaluateItemRepository evaluateItemRepository;

    @Resource
    private EvaluateItemValueRepository evaluateItemValueRepository;

    @Resource
    private ProductSkuService productSkuService;

    private ProductEntity getProduct(Long productId) {
        ProductEntity product = productRepository.selectByPrimaryKey(productId);
        if (Objects.isNull(product)) {
            throw Ex.business("商品不存在");
        }
        return product;
    }

    @Override
    public void resolveEvaluateItem(Long productId) {

        ProductEntity product = getProduct(productId);

        List<EvaluateListApiDTO> evaluateItemList = evaluateApiService.productEvaluateList(productId);
        log.info("商品ID: {}, 评估项列表: {}", productId, Jsons.toFormatJsonString(evaluateItemList));
        List<EvaluateListApiDTO> skuList = evaluateItemList.stream()
                .filter(evaluate -> Objects.equals(evaluate.getEvaluateType(), EvaluateTypeEnum.SKU.value())).collect(Collectors.toList());
        List<EvaluateListApiDTO> evaluateList = evaluateItemList.stream().filter(
                evaluate -> Objects.equals(evaluate.getEvaluateType(), EvaluateTypeEnum.ITEM.value())).collect(Collectors.toList());

        log.info("商品ID: {}, SKU列表: {}", productId, Jsons.toFormatJsonString(skuList));
        log.info("商品ID: {}, 评估列表: {}", productId, Jsons.toFormatJsonString(evaluateList));
        // 处理SKU列表 - 插入到AttributeItem和AttributeItemValue表
        processSkuList(product,skuList);
        
        // 生成SKU组合
        generateProductSkuCombinations(product, skuList);

        // 处理评估列表 - 插入到EvaluateItem和EvaluateItemValue表
        processEvaluateList(product,evaluateList);
    }

    /**
     * 处理SKU列表，将数据插入到AttributeItem和AttributeItemValue表
     */
    private void processSkuList(ProductEntity product, List<EvaluateListApiDTO> skuList) {
        for (EvaluateListApiDTO skuItem : skuList) {
            if (skuItem.getAttrName() == null || skuItem.getAttrName().trim().isEmpty()) {
                continue;
            }

            // 检查AttributeItem表中是否存在该attrName
            AttributeItemQuery attrQuery = new AttributeItemQuery();
            attrQuery.setAttrName(skuItem.getAttrName());
            attrQuery.setCategoryId(product.getCategoryId());
            AttributeItemEntity existingAttrItem = attributeItemRepository.selectOne(attrQuery);

            Long attrItemId;
            if (Objects.isNull(existingAttrItem)) {
                // 不存在则插入新的AttributeItem
                AttributeItemEntity newAttrItem = new AttributeItemEntity();
                newAttrItem.setAttrName(skuItem.getAttrName());
                newAttrItem.setCategoryId(product.getCategoryId());
                newAttrItem.setCategoryName(product.getCategoryName());
                newAttrItem.setStatus(1); // 默认状态为启用
                newAttrItem.setSort(0);
                newAttrItem.setCreateTime(new Date());
                attributeItemRepository.insertSelective(newAttrItem);
                attrItemId = newAttrItem.getAttrItemId();
            } else {
                attrItemId = existingAttrItem.getAttrItemId();
            }

            // 处理AttributeItemValue
            if (skuItem.getAttrValues() != null && !skuItem.getAttrValues().isEmpty()) {
                for (EvaluateValueApiDTO valueDto : skuItem.getAttrValues()) {
                    if (valueDto.getValueContent() == null || valueDto.getValueContent().trim().isEmpty()) {
                        continue;
                    }

                    // 检查AttributeItemValue表中是否存在该valueContent
                    AttributeItemValueQuery valueQuery = new AttributeItemValueQuery();
                    valueQuery.setAttrItemId(attrItemId);
                    valueQuery.setCategoryId(product.getCategoryId());
                    valueQuery.setValueContent(valueDto.getValueContent());
                    AttributeItemValueEntity existingValue = attributeItemValueRepository.selectOne(valueQuery);

                    if (existingValue == null) {
                        // 不存在则插入新的AttributeItemValue
                        AttributeItemValueEntity newValue = new AttributeItemValueEntity();
                        newValue.setAttrItemId(attrItemId);
                        newValue.setAttrName(skuItem.getAttrName());
                        newValue.setValueContent(valueDto.getValueContent());
                        newValue.setStatus(1); // 默认状态为启用
                        newValue.setSort(0);
                        newValue.setCreateTime(new Date());
                        newValue.setCategoryId(product.getCategoryId());
                        attributeItemValueRepository.insertSelective(newValue);
                    }
                }
            }
        }
    }

    /**
     * 处理评估列表，将数据插入到EvaluateItem和EvaluateItemValue表
     */
    private void processEvaluateList(ProductEntity product, List<EvaluateListApiDTO> evaluateList) {
        for (EvaluateListApiDTO evaluateItem : evaluateList) {
            if (evaluateItem.getAttrName() == null || evaluateItem.getAttrName().trim().isEmpty()) {
                continue;
            }

            // 检查EvaluateItem表中是否存在该itemName
            EvaluateItemQuery itemQuery = new EvaluateItemQuery();
            itemQuery.setItemName(evaluateItem.getAttrName());
            itemQuery.setCategoryId(product.getCategoryId());
            EvaluateItemEntity existingEvaluateItem = evaluateItemRepository.selectOne(itemQuery);

            Long evaluateItemId;
            if (existingEvaluateItem == null) {
                // 不存在则插入新的EvaluateItem
                EvaluateItemEntity newEvaluateItem = new EvaluateItemEntity();
                newEvaluateItem.setItemName(evaluateItem.getAttrName());
                newEvaluateItem.setSelectType(evaluateItem.getIsMultiSelect() != null && evaluateItem.getIsMultiSelect() ? 2 : 1); // 1-单选，2-多选
                newEvaluateItem.setStatus(1); // 默认状态为启用
                newEvaluateItem.setSort(0);
                newEvaluateItem.setCreateTime(new Date());
                newEvaluateItem.setCategoryId(product.getCategoryId());
                newEvaluateItem.setCategoryName(product.getCategoryName());
                evaluateItemRepository.insertSelective(newEvaluateItem);
                evaluateItemId = newEvaluateItem.getEvaluateItemId();
            } else {
                evaluateItemId = existingEvaluateItem.getEvaluateItemId();
            }

            // 处理EvaluateItemValue
            if (evaluateItem.getAttrValues() != null && !evaluateItem.getAttrValues().isEmpty()) {
                for (EvaluateValueApiDTO valueDto : evaluateItem.getAttrValues()) {
                    if (valueDto.getValueContent() == null || valueDto.getValueContent().trim().isEmpty()) {
                        continue;
                    }

                    // 检查EvaluateItemValue表中是否存在该valueContent
                    EvaluateItemValueQuery valueQuery = new EvaluateItemValueQuery();
                    valueQuery.setEvaluateItemId(evaluateItemId);
                    valueQuery.setValueContent(valueDto.getValueContent()); // 注意：这里用valueName字段
                    valueQuery.setCategoryId(product.getCategoryId());
                    EvaluateItemValueEntity existingValue = evaluateItemValueRepository.selectOne(valueQuery);

                    if (existingValue == null) {
                        // 不存在则插入新的EvaluateItemValue
                        EvaluateItemValueEntity newValue = new EvaluateItemValueEntity();
                        newValue.setEvaluateItemId(evaluateItemId);
                        newValue.setEvaluateItemName(evaluateItem.getAttrName());
                        newValue.setValueContent(valueDto.getValueContent());
                        newValue.setStatus(1); // 默认状态为启用
                        newValue.setSort(0);
                        newValue.setCategoryId(product.getCategoryId());
                        newValue.setCreateTime(new Date());
                        evaluateItemValueRepository.insertSelective(newValue);
                    }
                }
            }
        }
    }

    /**
     * 生成SKU组合
     * 从SKU列表中提取attrValues的valueContent，查询p_attribute_item_value获取attr_value_id，
     * 然后调用productSkuService.generateSkuCombinations生成SKU组合
     */
    private void generateProductSkuCombinations(ProductEntity product, List<EvaluateListApiDTO> skuList) {
        if (skuList == null || skuList.isEmpty()) {
            log.info("商品ID: {}, SKU列表为空，跳过SKU组合生成", product.getProductId());
            return;
        }

        // 第一步：收集所有的valueContent
        Set<String> valueContentSet = new HashSet<>();
        for (EvaluateListApiDTO skuItem : skuList) {
            if (skuItem.getAttrValues() == null || skuItem.getAttrValues().isEmpty()) {
                continue;
            }
            for (EvaluateValueApiDTO valueDto : skuItem.getAttrValues()) {
                if (valueDto.getValueContent() != null && !valueDto.getValueContent().trim().isEmpty()) {
                    valueContentSet.add(valueDto.getValueContent());
                }
            }
        }

        if (valueContentSet.isEmpty()) {
            log.warn("商品ID: {}, 未找到任何有效的属性值内容，跳过SKU组合生成", product.getProductId());
            return;
        }

        log.info("商品ID: {}, 收集到的属性值内容列表: {}", product.getProductId(), valueContentSet);

        // 第二步：批量查询所有valueContent对应的AttributeItemValueEntity
        AttributeItemValueQuery batchQuery = new AttributeItemValueQuery();
        batchQuery.setCategoryId(product.getCategoryId());
        List<AttributeItemValueEntity> allAttrValues = attributeItemValueRepository.selectList(batchQuery);

        // 第三步：构建valueContent到attrValueId的映射
        Map<String, Long> valueContentToIdMap = new HashMap<>();
        for (AttributeItemValueEntity entity : allAttrValues) {
            if (entity.getValueContent() != null && valueContentSet.contains(entity.getValueContent())) {
                valueContentToIdMap.put(entity.getValueContent(), entity.getAttrValueId());
            }
        }

        log.info("商品ID: {}, 查询到的属性值映射: {}", product.getProductId(), valueContentToIdMap);

        // 第四步：收集所有的属性值ID
        List<Long> attrValueIdList = new ArrayList<>();
        for (EvaluateListApiDTO skuItem : skuList) {
            if (skuItem.getAttrValues() == null || skuItem.getAttrValues().isEmpty()) {
                continue;
            }
            for (EvaluateValueApiDTO valueDto : skuItem.getAttrValues()) {
                if (valueDto.getValueContent() == null || valueDto.getValueContent().trim().isEmpty()) {
                    continue;
                }
                
                Long attrValueId = valueContentToIdMap.get(valueDto.getValueContent());
                if (attrValueId != null) {
                    attrValueIdList.add(attrValueId);
                    log.info("商品ID: {}, 找到属性值: {}, 属性值ID: {}", 
                            product.getProductId(), valueDto.getValueContent(), attrValueId);
                } else {
                    log.warn("商品ID: {}, 未找到属性值: {} 对应的attr_value_id", 
                            product.getProductId(), valueDto.getValueContent());
                }
            }
        }

        // 如果没有找到任何属性值ID，则不生成SKU组合
        if (attrValueIdList.isEmpty()) {
            log.warn("商品ID: {}, 未找到任何有效的属性值ID，跳过SKU组合生成", product.getProductId());
            return;
        }

        // 构建SkuGenerateDTO并调用生成SKU组合的方法
        SkuGenerateDTO skuGenerateDTO = new SkuGenerateDTO();
        skuGenerateDTO.setProductId(product.getProductId());
        skuGenerateDTO.setAttrValueList(attrValueIdList);

        log.info("商品ID: {}, 开始生成SKU组合，属性值ID列表: {}", product.getProductId(), attrValueIdList);
        
        try {
            Integer skuCount = productSkuService.generateSkuCombinations(skuGenerateDTO);
            log.info("商品ID: {}, SKU组合生成成功，生成数量: {}", product.getProductId(), skuCount);
        } catch (Exception e) {
            log.error("商品ID: {}, SKU组合生成失败", product.getProductId(), e);
            throw Ex.business("SKU组合生成失败: " + e.getMessage());
        }
    }
}
